package com.jfirer.validator.constraint.validator;

import java.lang.reflect.Array;
import java.util.Collection;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Size;

public class SizeValidator implements ConstraintValidator<Size, Object>
{
    private int min;
    private int max;
    
    @Override
    public void initialize(Size constraintAnnotation)
    {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
        if (min > max)
        {
            throw new UnsupportedOperationException("min 必须小于max");
        }
    }
    
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context)
    {
        if (value == null)
        {
            return true;
        }
        int size = 0;
        if (value instanceof String)
        {
            String str = (String) value;
            size = str.length();
        }
        else if (value instanceof Collection<?>)
        {
            Collection<?> collection = (Collection<?>) value;
            size = collection.size();
        }
        else if (value.getClass().isArray())
        {
            size = Array.getLength(value);
        }
        return size >= min && size <= max;
    }
    
}
